import time
from django.utils.deprecation import MiddlewareMixin
from .models import RequestLog


class RequestTimingMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request.start_time = time.time()

    def process_response(self, request, response):
        if hasattr(request, 'start_time'):
            duration = time.time() - request.start_time

            # Log the request information
            RequestLog.objects.create(
                path=request.path,
                method=request.method,
                status_code=response.status_code,
                duration=duration
            )

            # Add X-Response-Time header
            response['X-Response-Time'] = f"{duration:.2f}s"

        return response
